//
//  Fish_WorryPublishViewController.swift
//  WoodenFishApp
//
//  Created by mac on 2023/11/2.
//  Copyright © 2023 Fish_. All rights reserved.
//

import UIKit

class Fish_WorryPublishViewController: BasicViewController {
    
    var imgArr:[String] = []
    var typeString = ""
    var descString = ""
    
    private lazy var table: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.showsVerticalScrollIndicator = false
        view.register(PublishTopCell.self, forCellReuseIdentifier: PublishTopCell.description())
        view.register(PublishBottomCell.self, forCellReuseIdentifier: PublishBottomCell.description())
        view.register(PublishMiddleCell.self, forCellReuseIdentifier: PublishMiddleCell.description())
        return view
    }()
    private lazy var doneButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = .setTypeFace(16.Fit,type: .medium)
        button.setTitleColor(mainColor, for: .normal)
        button.setTitle("Post", for: .normal)
        button.backgroundColor = .black
        button.layer.cornerRadius = 25
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.subviews {
            table
            doneButton
        }
        doneButton.left(30.Fit).right(30.Fit).height(50).bottom(TabbarSafeBottomMargin + 5.Fit)
        doneButton.addAct {
            Toast_View_Tool.show()
            guard self.typeString.count != 0 else {
                Toast_View_Tool.show(type: .error,text: "The type cannot be empty.")
                return
            }
            guard self.descString.count != 0 else {
                Toast_View_Tool.show(type: .error,text: "The description cannot be empty.")
                return
            }
            guard self.imgArr.count != 0 else {
                Toast_View_Tool.show(type: .error,text: "The picture cannot be empty.")
                return
            }
            Toast_View_Tool.show()
            let date = Date()
            let timeFormatter = DateFormatter()
            timeFormatter.dateFormat = "MM-dd HH:mm"
            let strNowTime = timeFormatter.string(from: date) as String
            var dict:[String:Any] = [:]
            dict["userId"] = USEINFOMODEL.id
            dict["icon"] = USEINFOMODEL.headImage
            dict["info"] = USEINFOMODEL.name
            dict["info0"] = self.typeString
            dict["info1"] = self.descString
            dict["info2"] = self.imgArr.joined(separator: "@@")
            dict["info3"] = "0"
            dict["info4"] = strNowTime
            dict["password"] = "0"
            RT.createHouse(paraInfo: dict) { s in
                Toast_View_Tool.show(type: .success,text: "Success")
                self.navigationController?.popViewController(animated: true)
            }
        }
        table.left(0).right(0).top(0)
        table.Bottom == doneButton.Top - 10.Fit
        table.reloadData()
    }
    
}


extension Fish_WorryPublishViewController:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishMiddleCell.description(), for: indexPath) as! PublishMiddleCell
            cell.imgArr = self.imgArr
            cell.upImgBlock = { img in
                self.imgArr.append(img)
                self.table.reloadData()
            }
            cell.deleteBlock = { index in
                self.imgArr.remove(at: index)
                self.table.reloadData()
            }
            return cell
        }
        if indexPath.section == 2{
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishBottomCell.description(), for: indexPath) as! PublishBottomCell
            cell.doneBlock = { name in
                self.descString = name
            }
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishTopCell.description(), for: indexPath) as! PublishTopCell
        cell.doneBlock = { name in
            self.typeString = name
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 2{
            return 160.Fit
        }
        if indexPath.section == 1{
            var h:CGFloat = 0
            if imgArr.count/2 == 0{
                h = CGFloat((imgArr.count/2 + 1)) * 170.Fit + 65.Fit
            }else{
                h = CGFloat(imgArr.count/2 + 1) * 170.Fit + 65.Fit
            }
            print("heightForRowAt==-======   ")
            print(imgArr.count/2)
            print(h)
            return h
        }
        return 100.Fit
    }
}


class PublishTopCell: UITableViewCell {
    
    let titL = UILabel.initV(UIFont.setTypeFace(18.Fit,type: .medium), text: "Pet type", textColor:titleColor)
    let addB = UIButton.initV(img: "")
    var doneBlock:((String) -> Void)?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        contentView.subviews {
            titL
            addB
        }
        titL.left(15.Fit).top(15.Fit).right(15.Fit).height(40.Fit)
        addB.left(15.Fit).top(60.Fit).right(15.Fit).height(40.Fit)
        addB.setAllCorners(corner: 20.Fit)
        addB.backgroundColor = .white
        
        addB.setTitle("Choose", for: .normal)
        addB.setTitleColor(.blackComponent(0.3), for: .normal)
        addB.contentHorizontalAlignment = .left
        addB.titleEdgeInsets = .init(top: 0, left: 30.Fit, bottom: 0, right: 0)
        addB.addAct {
            let view1 = Card_ListView()
            view1.doneBlock = { name,index in
                self.doneBlock?(name)
                self.addB.setTitle(name, for: .normal)
                self.addB.setTitleColor(.blackComponent(1), for: .normal)
            }
            let page = Pop_Up_Custom_View(config: PopUpViewConfig(view: view1, size: CGSize(width: screenWidth - 30.Fit, height: 450.Fit)),top: NavHeight + 130.Fit,right: 15.Fit)
            page.isCloseFromClean = true
            page.animatedPop()
        }
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

class PublishMiddleCell: UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource {
    
    let titL = UILabel.initV(UIFont.setTypeFace(18.Fit,type: .medium), text: "Picture", textColor:titleColor)
    var imgArr:[String] = []{
        didSet{
            self.titL.text = "Picture \(imgArr.count)/6"
            self.imgListView.reloadData()
            self.imgListView.reloadData()
        }
    }
    var upImgBlock:((String) -> Void)?
    var deleteBlock:((Int) -> Void)?
    
    private lazy var imgListView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 10.Fit
        layout.minimumInteritemSpacing = 10.Fit
        layout.itemSize = .init(width: 140.Fit, height: 160.Fit)
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.register(ImgList_Item.self, forCellWithReuseIdentifier: ImgList_Item.description())
        view.contentInset = .init(top: 0, left: 15.Fit, bottom: 0, right: 50.Fit)
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.bounces = false
        return view
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        contentView.subviews {
            titL
            imgListView
        }
        titL.left(15.Fit).top(15.Fit).right(15.Fit).height(40.Fit)
        imgListView.left(0).width(screenWidth).bottom(0)
        imgListView.Top == titL.Bottom + 10.Fit
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imgArr.count + 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let item = collectionView.dequeueReusableCell(withReuseIdentifier: ImgList_Item.description(), for: indexPath) as! ImgList_Item
        if indexPath.item < imgArr.count{
            item.contentI.image = .init(named: "")
            item.name = imgArr[indexPath.item]
            item.closeB.isHidden = false
        }else
        {
            item.contentI.image = .init(named: "picture_add")
            item.closeB.isHidden = true
        }
        item.closeB.addAct {
            self.deleteBlock?(indexPath.item)
        }
        return item
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard indexPath.item == imgArr.count,imgArr.count < 6 else {
            return
        }
        let page = Edit_Choose_Photo_Interface(type: .photoPicker)
        page.chooseImageCompletion = { [weak self] image in
           Toast_View_Tool.show()
           RT.uploadCoverImage(file: (self?.imageToBase64String(image: image))!) { [self] (dict) in
               Toast_View_Tool.dismiss()
               self?.upImgBlock?(dict.url!)
           }
        }
        UIApplication.topViewController()?.present(page, animated: true)
    }
    
    func imageToBase64String(image:UIImage)->Data?{
        let imageData = image.resetImgSize()
        return imageData
    }

}

class ImgList_Item: UICollectionViewCell {
    
    let contentI = UIImageView.initImgView(img: "")
    let closeB = UIButton.initV(img: "close")
    var name:String?{
        didSet{
            if let url = URL(string: name ?? "") {
                self.contentI.kf.setImage(with: url)
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.subviews {
            contentI
            closeB
        }
        contentI.fillContainer()
        contentI.setAllCorners(corner: 10.Fit)
        closeB.size(30.Fit).top(5.Fit).right(5.Fit)
        closeB.addAct {
            
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


class PublishBottomCell: UITableViewCell {
    
    let titL = UILabel.initV(UIFont.setTypeFace(18.Fit,type: .medium), text: "Describe", textColor:titleColor)
    private lazy var descView: Custom_TextView = {
        let view = Custom_TextView()
        view.backgroundColor = UIColor.white
        view.textContainerInset = UIEdgeInsets(top: 20.Fit, left: 20.Fit, bottom: 20.Fit, right: 20.Fit)
        view.tintColor = .black
        view.textColor = .black
        view.placeHolderColor = UIColor.color(hexString: "#999999",alpha: 1)
        view.placeHolder = "Say something"
        view.returnKeyType = .done
        view.font = .setTypeFace(16.Fit,type: .medium)
        return view
    }()
    var doneBlock:((String) -> Void)?
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        contentView.subviews {
            titL
            descView
        }
        titL.left(15.Fit).top(15.Fit).right(15.Fit).height(40.Fit)
        descView.left(15.Fit).top(60.Fit).right(15.Fit).height(120.Fit)
        descView.setAllCorners(corner: 20.Fit)
        descView.backgroundColor = .white
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardHide), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    @objc func keyboardHide() -> Void {
        guard self.descView.text.isBlank == false else {
            return
        }
        self.doneBlock?(self.descView.text)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
